package com.ruoyi.common.core.utils;

import com.ruoyi.common.core.exception.CheckedException;
import com.ruoyi.common.core.exception.InnerAuthException;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.exception.auth.NotLoginException;
import com.ruoyi.common.core.exception.auth.NotPermissionException;
import com.ruoyi.common.core.exception.auth.NotRoleException;
import com.ruoyi.common.core.exception.base.BaseException;
import com.ruoyi.common.core.exception.job.TaskException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * 错误信息处理类。
 *
 * @author ruoyi
 */
@Slf4j
public class ExceptionUtil {

  /**
   * 获取exception的详细错误信息。
   */
  public static String getUserMessage(Throwable e) {
    if (e == null) {
      return "服务异常[null]";
    }
    return  deliverException(e, true);

  }

  /**
   * 获取exception的详细错误信息。
   */
  public static String getSimpleMessage(Throwable e) {
    if (e == null) {
      return "异常信息[null]空";
    }
    return  deliverException(e, false);
  }

  /**
   * 获取exception的详细错误信息。
   */
  public static String getExceptionMessage(Throwable e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw, true));
    return sw.toString();
  }

  public static String getRootErrorMessage(Exception e) {
    Throwable root = ExceptionUtils.getRootCause(e);
    root = (root == null ? e : root);
    if (root == null) {
      return "";
    }
    String msg = root.getMessage();
    if (msg == null) {
      return "null";
    }
    return StringUtils.defaultString(msg);
  }

  private static String deliverException(Throwable e, boolean forApp) {
    if (e instanceof ServiceException) {
      return ((ServiceException) e).getMessage();
    }
    if (e instanceof BaseException) {
      return Optional.ofNullable(((BaseException) e).getMessage())
          .orElse(((BaseException) e).getDefaultMessage());
    }
    if (e instanceof TaskException
        || e instanceof NotLoginException
        || e instanceof NotPermissionException
        || e instanceof NotRoleException
        || e instanceof CheckedException
        || e instanceof InnerAuthException
    ) {
      return e.getMessage();
    }
    return forApp ? "服务器异常,请耐心等待恢复,或者联系管理员" :
        e.getCause() == null ? e.getMessage() : e.getCause().getMessage();
  }
}
